package com.zyc.factory;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例工厂
 * @author zyc
 * @create 2022--05--11 10:00
 */
public final class SingletonFactory {
    private static final Map<String, Object> OBJECT_MAP = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> clazz) {
        String key = clazz.getName();
        if (OBJECT_MAP.containsKey(key)) {
            // 强制转换
            return clazz.cast(OBJECT_MAP.get(key));
        } else {
            return clazz.cast(OBJECT_MAP.computeIfAbsent(key, k -> {
                try {
                    Object instance = clazz.getDeclaredConstructor().newInstance();
                    return instance;
                } catch (InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }));
        }
    }
}
